import { useState, useEffect } from 'react';
import { useMutation, useQuery } from 'react-query';
import { request, TResData } from '@/request';

type User = {
   username: string;
   location: string;
   email: string;
   [key: string]: any;
};

const Profile = () => {
   const { data } = useQuery<TResData<User>>('getUser', () =>
      request<User>('/user')
   );

   const mutation = useMutation((user: User) =>
      request<User>('/user', {
         method: 'PATCH',
         data: user,
         showSuccess: true,
      })
   );

   const [form, setForm] = useState<User>({
      username: '',
      location: '',
      email: '',
   });

   useEffect(() => {
      if (data) {
         setForm({
            username: data.data.username,
            location: data.data.location,
            email: data.data.email,
         });
      }
   }, [data]);

   const handleChange = (e) => {
      const { value, name } = e.target;
      setForm({
         ...form,
         [name]: value,
      });
   };

   const handleSubmit = () =>{
      mutation.mutate({
         username: form.username,
         location: form.location,
         email: form.email,
      })

   }

   return (
      <div className="box">
         <div className="flex flex-col w-1/2 space-y-2">
            <div className="form-item-content">
               <label className="w-1/4">Username</label>
               <input
                  value={form.username}
                  name="username"
                  onChange={handleChange}
               />
            </div>
            <div className="form-item-content">
               <label className="w-1/4">Email</label>
               <input value={form.email} name="email" onChange={handleChange} />
            </div>
            <div className="form-item-content">
               <label className="w-1/4">Location</label>
               <input
                  value={form.location}
                  name="location"
                  onChange={handleChange}
               />
            </div>
            <div className="text-right pt-4">
               <button onClick={handleSubmit}>Submit</button>
            </div>
         </div>
      </div>
   );
};

export default Profile;
